package org.java.auth.service;

import org.java.auth.vo.SecurityUserDetails;
import org.java.user.api.UserCenter;
import org.java.user.api.domain.Role;
import org.java.user.api.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

//远程的用户信息服务，要去调用远程的用户接口得到用户信息
public class RemoteUserDetailsService implements UserDetailsService {

    @Autowired
    private UserCenter userCenter;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        先获取传进来的用户名，查询是否有这个用户
        User user = userCenter.loadUserByName(username);
        if (user==null){
           throw  new  UsernameNotFoundException("无法找到" + username + "对应的用户！");
        }

        Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
        List<Role>roles = user.getRoles();
        roles.forEach(role->{
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_"+ role.getRoleKey());
            authorities.add(authority);
        });

        return new SecurityUserDetails(user,authorities);
    }

}